<?php
if (!class_exists("TemplatePatterns")) include_once dirname(__FILE__).'/TemplatePatterns.class.php';
class BackPath {
	const LINK 				= "link";
	const LABEL 			= "label";
	const IMAGE 			= "image";
	
	private $_itemRender;
	private $_list;
	
	function __construct() {
		$this->_list = array();
	}
	
	public function add($link_url, $label = '', $image_url = ''){
		$item = array();
		$item[self::LINK] = $link_url;
		if ($label != '')
			$item[self::LABEL] = $label;
		if ($image_url != '')
			$item[self::LINK] = $image_url;
		
		array_push($this->_list, $item);
	}
	
	public function draw($itemRender, $glue) {
		$result = array();
		if ($itemRender != "")
			$this->_itemRender = $itemRender;
		$itemsArray = array();
		preg_match_all(TemplatePatterns::tvar, $this->_itemRender, $itemsArray);		
		foreach ($this->_list as $key => $item){
			$string = $this->_itemRender;
			foreach($itemsArray[1] as $k => $v){
				if (strpos($v, $this->REPEAT_DELIMER) > 0){
					$repeat = preg_split("/\\$this->REPEAT_DELIMER/", $v);
					$countRepeat = count($repeat);
					$keyRepeat = $key - $countRepeat * floor($key/$countRepeat);
					$string = str_replace($itemsArray[0][$k], $repeat[$keyRepeat], $string);
				} else {
					if (isset($item[$v]))
						$string = str_replace($itemsArray[0][$k], $item[$v], $string);
				}
			}
			array_push($result, $string);
		}
		echo join($glue, $result);
	}
	
	public function getLinkbyIndex($index) {
		return $this->_list[$index][self::LINK];
	}
	
	public function getLastLink() {
		return $this->_list[count($this->_list)-1][self::LINK];
	}
	
	public function length() {
		return count($this->_list);
	}
}
?>